package com.kizuki.thread;

import org.junit.Test;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

// JUC常用辅助类
// CountDownLatch CyclicBarrier 参考Collection类的例子
public class TestSemaphore {

    @Test
    public void test() throws InterruptedException {
        // 限流
        Semaphore semaphore = new Semaphore(2);

        for (int i = 1; i <= 6; i++) {
            Thread thread = new Thread(() -> {
                try {
                    semaphore.acquire(); // 得到
                    System.out.println(Thread.currentThread().getName() + "抢到了车位");
                    TimeUnit.SECONDS.sleep(2);
                    System.out.println(Thread.currentThread().getName() + "离开了车位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release(); // 释放
                }

            }, String.valueOf(i));
            thread.start();
        }

        TimeUnit.SECONDS.sleep(8);
    }

}
